package com.le.tester.imooc.masterJUC.lock.reentrantlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：reentrantLock被打断
 */
public class LockDemo {
    public static void main(String[] args) {
        new LockDemo().init();
    }

    private void init() {
        final Output output = new Output();
        new Thread(() -> {
            while (true) {
                try {
                    //两边控制的时间不一样，减少了出错的概率
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                output.output("悟空");
            }
        }).start();
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                output.output("大师兄");
            }
        }).start();

    }

    static class Output {
        Lock lock = new ReentrantLock();

        //拆分字符串，打印拆分的字符
        public void output(String name) {
            int length = name.length();
            //需要保证线程进来打印的顺序
            lock.lock();
            try {
                for (int i = 0; i < length; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println(";");
            } finally {
                lock.unlock();
            }
        }
    }

}
